﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Web.Routing;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq.Expressions;

namespace MvcShop.Extensions.Html
{
    public static class EnumToSelectExtensions
    {
        // DropDownList for Nested Types
        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
        public static MvcHtmlString EDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {
            return DropDownListFor(htmlHelper, expression/*, null  optionLabel */, null /* htmlAttributes */);
        }
 
        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
        public static MvcHtmlString EDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) {
            return DropDownListFor(htmlHelper, expression /*, null optionLabel */, new RouteValueDictionary(htmlAttributes));
        }

        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
        {
            SelectList selectList = null;

            if (typeof(TProperty).IsEnum)
            {
                var values = from TProperty e in Enum.GetValues(typeof(TProperty))
                             select new
                             {
                                 Value = Convert.ToInt32(e),
                                 Text = e.ToString()
                             };
                selectList = new SelectList(values, "Value", "Text", ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model);
            }

            return SelectExtensions.DropDownListFor(htmlHelper, expression, selectList /* optionLabel */, htmlAttributes);
        }
    }
}
